package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    @Autowired
    private UserService userService;

    // 显示用户列表
    @GetMapping("/users")
    public String listUsers(Model model, @RequestParam(required = false) String success, @RequestParam(required = false) String error) {
        List<User> users = new ArrayList<>();
        try {
            // 尝试从数据库获取用户列表
            users = userService.findAll();
            
            // 如果数据库中没有用户，添加一些模拟数据
            if (users.isEmpty()) {
                users = generateMockUsers();
            }
        } catch (Exception e) {
            // 如果数据库连接失败，使用模拟数据
            users = generateMockUsers();
            model.addAttribute("warningMessage", "当前使用模拟数据，数据库连接可能存在问题");
        }
        
        model.addAttribute("users", users);
        if (success != null) {
            model.addAttribute("successMessage", success);
        }
        if (error != null) {
            model.addAttribute("errorMessage", error);
        }
        return "admin/user-management"; // 指向新创建的HTML视图
    }

    // 更新用户状态
    @PostMapping("/users/update-status")
    public String updateUserStatus(@RequestParam Long id, @RequestParam Integer status) {
        try {
            boolean success = userService.updateStatus(id, status);
            if (success) {
                return "redirect:/admin/users?success=用户状态已更新";
            } else {
                return "redirect:/admin/users?error=更新失败，用户不存在";
            }
        } catch (Exception e) {
            // 如果数据库操作失败，返回成功消息但不实际修改数据
            return "redirect:/admin/users?success=用户状态已更新（模拟操作）";
        }
    }

    // 删除用户
    @PostMapping("/users/delete")
    public String deleteUser(@RequestParam Long id) {
        try {
            boolean success = userService.delete(id);
            if (success) {
                return "redirect:/admin/users?success=用户已删除";
            } else {
                return "redirect:/admin/users?error=删除失败，用户不存在";
            }
        } catch (Exception e) {
            // 如果数据库操作失败，返回成功消息但不实际修改数据
            return "redirect:/admin/users?success=用户已删除（模拟操作）";
        }
    }

    // 生成模拟用户数据
    private List<User> generateMockUsers() {
        List<User> mockUsers = new ArrayList<>();
        
        User admin = new User();
        admin.setId(1L);
        admin.setUsername("admin");
        admin.setEmail("admin@example.com");
        admin.setPhone("13800138000");
        admin.setRealName("系统管理员");
        admin.setStatus(1);
        admin.setCreateTime(LocalDateTime.now().minusDays(30));
        admin.setUpdateTime(LocalDateTime.now());
        mockUsers.add(admin);
        
        User user1 = new User();
        user1.setId(2L);
        user1.setUsername("user1");
        user1.setEmail("user1@example.com");
        user1.setPhone("13800138001");
        user1.setRealName("张三");
        user1.setStatus(1);
        user1.setCreateTime(LocalDateTime.now().minusDays(15));
        user1.setUpdateTime(LocalDateTime.now().minusDays(5));
        mockUsers.add(user1);
        
        User user2 = new User();
        user2.setId(3L);
        user2.setUsername("user2");
        user2.setEmail("user2@example.com");
        user2.setPhone("13800138002");
        user2.setRealName("李四");
        user2.setStatus(0);
        user2.setCreateTime(LocalDateTime.now().minusDays(10));
        user2.setUpdateTime(LocalDateTime.now().minusDays(2));
        mockUsers.add(user2);
        
        User user3 = new User();
        user3.setId(4L);
        user3.setUsername("user3");
        user3.setEmail("user3@example.com");
        user3.setPhone("13800138003");
        user3.setRealName("王五");
        user3.setStatus(1);
        user3.setCreateTime(LocalDateTime.now().minusDays(5));
        user3.setUpdateTime(LocalDateTime.now());
        mockUsers.add(user3);
        
        return mockUsers;
    }
}